import Duck from 'extensible-duck'
import produce from 'immer'
import { createSelector } from 'reselect'

const selectMouseWheel = state => state.canvas.mouseWheel

const imageScaleSelector = createSelector(
  selectMouseWheel,
  (wheelDeltaY) => {
    let scale
    if (wheelDeltaY >= 0) {
      scale = wheelDeltaY + 1
    } else {
      scale = 1 / (-1 * wheelDeltaY + 1)
    }
    return scale
  },
)

export default new Duck({
  namespace: 'label',
  store: 'canvas',
  types: [
    'SET_WINDOW_SIZE',
    'SET_MOUSE_WHEEL',
    'SET_COORDINATE',
    'INIT_ITEM_IMAGE',
    'INIT_MOUSE_WHEEL',
    'TOOGLE_PAN',
  ],
  initialState: {
    coodinate: {
      x: 0,
      y: 0,
    },
    mouseWheel: 0,
    pan: false,
  },
  reducer: produce((draft, action, duck) => {
    switch (action.type) {
      case duck.types.SET_WINDOW_SIZE:
        draft.windowSize = action.value
        break
      case duck.types.SET_MOUSE_WHEEL:
        draft.mouseWheel += action.value
        break
      case duck.types.INIT_MOUSE_WHEEL:
        draft.mouseWheel = action.value
        break
      case duck.types.SET_COORDINATE:
        draft.coodinate = action.value
        break
      case duck.types.TOOGLE_PAN:
        draft.pan = !draft.pan
        break
      default:
        break
    }
  }),
  selectors: {
    isInitSize: state => state.canvas.windowSize !== undefined,
    windowSize: state => state.canvas.windowSize,
    isPanActive: state => state.canvas.pan,
    coodinate: state => state.canvas.coodinate,
    imageScale: imageScaleSelector,
  },
  creators: duck => ({
    actionSetWindowSize: value => ({ type: duck.types.SET_WINDOW_SIZE, value }),
    actionSetMouseWheel: value => ({ type: duck.types.SET_MOUSE_WHEEL, value }),
    actionInitMouseWheel: value => ({ type: duck.types.INIT_MOUSE_WHEEL, value }),
    actionSetCoordinate: value => ({ type: duck.types.SET_COORDINATE, value }),
    actionInitItemImage: () => ({ type: duck.types.INIT_ITEM_IMAGE }),
    actionTooglePan: () => ({ type: duck.types.TOOGLE_PAN }),
  }),
})
